import axios, { HttpStatusCode } from 'axios'
import { MessagePlugin } from 'tdesign-vue-next'
import router from '@/router'

const baseURL = import.meta.env['VITE_API_URL']

const handleError = async (error: any) => {
  if (error.response.status === HttpStatusCode.Unauthorized) {
    MessagePlugin.closeAll()
    MessagePlugin.info('登录已过期，请重新登录！').then(() => {
      router.push('/login')
    })
  }
  if (error.response.status === HttpStatusCode.Forbidden) {
    MessagePlugin.closeAll()
    MessagePlugin.info('未登录，禁止访问！').then(() => {
      router.push('/login')
    })
  }
  return Promise.reject(error)
}

const createAxiosInstance = () => {
  const instance = axios.create({
    baseURL,
    timeout: 10000,
    withCredentials: true
  })

  instance.interceptors.request.use(
    (config) => {
      config.headers['Authorization'] = 'MaoJiuYuQi'
      config.headers['Content-Type'] = 'application/json'
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use((response) => {
    return response.data
  }, handleError)

  return instance
}

const instance = createAxiosInstance()

export const get = (url: string): Promise<any> => {
  return instance.get(url)
}

export const post = (url: string, data: object = {}): Promise<any> => {
  return instance.post(url, data)
}

export const apiUrl = (url = ''): any => {
  if (url[0] !== '/') {
    url = '/' + url
  }
  return baseURL + url
}

export default instance
